package socketWin

import (
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
	"smarteye"

	"jk/jklog"
)

type connData struct {
	se *smarteye.SmartEye
}

type NetWin struct {
	*walk.MainWindow
	submit  *walk.PushButton
	input   *walk.TextEdit
	display *walk.TextEdit
	data    connData
}

func (nw *NetWin) connSend(value string) error {
	nw.data.se = smarteye.NewSmartEye("192.168.6.155", 9701)
	err := nw.data.se.ConnectServer()
	if err != nil {
		return err
	}
	wl := nw.data.se.WriteRequest(value)
	jklog.L().Infoln("write [", value, " ] of len ", wl)

	return nil
}

func (nw *NetWin) sendAndResp() {
	str := nw.input.Text()
	err := nw.connSend(str)
	if err != nil {
		walk.MsgBox(nw, "发送", "连接服务器失败", walk.MsgBoxOK)
		return
	}

	go func() {
		var buf []byte
		var ch chan int
		ch <- nw.data.se.Read(buf)
		select {
		case ch <- 0:
			walk.MsgBox(nw, "响应", "获取返回失败", walk.MsgBoxOK)
			break
		default:
			jklog.L().Infoln("buf: ", buf)
			break
		}
	}()
}

func NetWindow(parent walk.Window) {
	/** some init */
	mw := new(NetWin)

	/* init main windows element */
	main := MainWindow{
		AssignTo: &mw.MainWindow,
		Title:    "SmartEye Client",
		MinSize:  Size{600, 480},
		Layout:   VBox{},
		Children: []Widget{
			TextEdit{
				AssignTo: &mw.input,
			},
			PushButton{
				AssignTo:  &mw.submit,
				Text:      "发送",
				OnClicked: mw.sendAndResp,
			},
			TextEdit{
				AssignTo: &mw.display,
				ReadOnly: true,
			},
		},
	}

	err := main.Create()
	if err != nil {
		jklog.L().Fatal(err)
	}

	mw.Run()
}
